const fs = require("fs");
const path = require("path");
const viewRoot = `./admin/app/view`;
function sectionPath(path, file) {
    return `${viewRoot}/sections/${path}/index.${file}`;
}

function staticPath(path) {
    return `./admin/app/static/${path}`;
}

function includePath(path, file) {
    return `${viewRoot}/snippets/${path}/index.${file}`;
}

function readFile(file) {
    return fs.readFileSync(file, "utf-8");
}

function writeFile(targetFile, content) {
    const dir = path.dirname(targetFile);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
    fs.writeFileSync(targetFile, content);
}

function buildRoot(file) {
    return "./src/template" + file;
}

function buildSectionPath(themName, fileName) {
    return buildRoot("/" + themName + "/sections/" + snippetsName(fileName) + ".liquid");
}

function buildAssetsPath(themName, Suffix) {
    return buildRoot(`/${themName}/assets/${themName}.${Suffix}`);
}

function buildConfigPath(themName, file) {
    return buildRoot(`/${themName}/config/${file}`);
}

function buildSnippetPath(themName, fileName) {
    return buildRoot("/" + themName + "/snippets/" + snippetsName(fileName) + ".liquid");
}

/**
 * @description: 获取全局数据
 * @param {*} data 全局配置
 * @return {*}
 */
function getGlobalValue(globalData) {
    //数据集合
    const setData = {};
    globalData.forEach((item) => {
        item.settings.forEach((setting) => {
            if (setting.id) {
                setData[setting.id] = setting.default;
            }
        });
    });
    return setData;
}

function snippetsName(path) {
    return path.replace("/", "_");
}

// 替换组件名称变量
function replaceComponentName(content, path) {
    const _COMPONENT_NAME_ = path.replace(/.\/admin\/app\/view\/([\s\S]*?)\/index\.[\s\S]*/g, "$1");
    return content.replace(/_COMPONENT_NAME_ATTR_/g, `${_COMPONENT_NAME_.replace(/\//g, "-")}`).replace(/_COMPONENT_NAME_/g, `'${_COMPONENT_NAME_.replace(/\//g, "_")}'`);
}

module.exports = {
    snippetsName,
    replaceComponentName,
    staticPath,
    getGlobalValue,
    buildConfigPath,
    sectionPath,
    buildAssetsPath,
    writeFile,
    includePath,
    readFile,
    buildRoot,
    buildSectionPath,
    buildSnippetPath
};
